<template lang='pug'>
  section.bg
    van-nav-bar(
      title="我的订单"
      left-arrow
      @click-left="$router.back()"
      )
    van-tabs(v-model="currentIndex" sticky :swipe-threshold="5")
      van-tab(title="全部")
        van-list(
          v-model="isLoading"
          :finished="finished"
          @load="getOrderALL"
          :offset="offset"
          )
          //- .loading(v-show="isLoading"): van-loading
          empty(title="您还没有订单，快去买个东西吧 😊" v-show="!isLoading && (!orders || !orders.length)")
          .order(v-for="order in orders")
            .order-status {{order.status | orderStatus}}
            van-card(
              :num="orderDetail.quantity"
              tag="热卖"
              :price="orderDetail.currentUnitPrice"
              :title="orderDetail.productName"
              desc=""  
              :thumb="orderDetail.productImage"
              v-for="orderDetail in order.orderDetails"
              :key="orderDetail.id"
              @click.native="$router.push('/detail/' + orderDetail.productId)"
              )
            .total
              |共计{{order.orderDetails | totalNum}}件商品  合计：
              span.amount ¥{{order.payment}}
            
            .control(v-if="order.status === 0 || order.status === 30")
              van-button(size="small" plain round type="default" @click="delOrder(order)") 删除订单
            .control(v-else-if="order.status === 10")
              van-button(size="small" plain round type="default" @click="cancelOrder(order)") 取消订单
              van-button(size="small" plain round type="danger" @click="pay(order)") 立即付款

            .control(v-else-if="order.status === 20")
              van-button(size="small" plain round type="default" @click="remind") 提醒发货

            .control(v-else-if="order.status === 40")
              van-button(size="small" plain round type="default" @click="$router.push('/logistics/' + order.orderDetails[0].id)") 查看物流
              van-button(size="small" plain round type="danger" @click="receivingGoods(order.id)") 确认收货

            .control(v-else-if="order.status === 50")
              van-button(size="small" plain round type="default" @click="$router.push('/logistics/' + order.id)") 查看物流

      van-tab(title="待付款")
        van-list(
          v-model="isLoading"
          :finished="unpayfinished"
          @load="getOrderByStatus(10)"
          :offset="offset"
          )
          //- .loading(v-show="isLoading"): van-loading
          empty(title="您没有未付款的订单 😊" v-show="!isLoading && (!unpayOrders || !unpayOrders.length)")
          .order(v-for="order in unpayOrders")
            .order-status {{order.status | orderStatus}}
            van-card(
              :num="orderDetail.quantity"
              tag="热卖"
              :price="orderDetail.currentUnitPrice"
              :title="orderDetail.productName"
              desc=""  
              :thumb="orderDetail.productImage"
              v-for="orderDetail in order.orderDetails"
              :key="orderDetail.id"
              )
            .total
              |共计{{order.orderDetails | totalNum}}件商品  合计：
              span.amount ¥{{order.payment}}

            .control
              van-button(size="small" plain round type="default" @click="cancelOrder(order)") 取消订单
              van-button(size="small" plain round type="danger" @click="pay(order)") 立即付款
      van-tab(title="待发货")
        van-list(
          v-model="isLoading"
          :finished="hasntLogisticsfinished"
          @load="getOrderByStatus(20)"
          :offset="offset"
          )
          //- .loading(v-show="isLoading"): van-loading
          empty(title="您没有待发货的订单 😊" v-show="!isLoading && (!hasntLogisticsOrders || !hasntLogisticsOrders.length)")
          .order(v-for="order in hasntLogisticsOrders")
            .order-status {{order.status | orderStatus}}
            van-card(
              :num="orderDetail.quantity"
              tag="热卖"
              :price="orderDetail.currentUnitPrice"
              :title="orderDetail.productName"
              desc=""  
              :thumb="orderDetail.productImage"
              v-for="orderDetail in order.orderDetails"
              :key="orderDetail.id"
              )
            .total
              |共计{{order.orderDetails | totalNum}}件商品  合计：
              span.amount ¥{{order.payment}}

            .control
              van-button(size="small" plain round type="default" @click="remind") 提醒发货
              van-button(size="small" plain round type="default" @click="cancelOrder(order)") 取消订单
              //- van-button(size="small" plain round type="danger" @click="pay(order)") 立即付款

</template>

<script type='text/ecmascript-6'>
  import pay from '~/assets/js/pay'
  import { compare } from '~/assets/js/util'
  import { pageSize, offset } from '~/config/search'
  import empty from '~/components/empty'

  export default {
    components: {
      empty
    },
    data() {
      return {
        currentIndex: 0,
        tabs: ['全部', '待付款', '待发货', '待收货', '待评价'],
        orders: [],
        isLoading: false,
        finished: false,
        pageNum: 1,
        pageSize,
        offset,
        unpayOrders: [],
        unpayPageNum: 1,
        unpayfinished: false,
        hasntLogisticsOrders: [],
        hasntLogisticsPageNum: 1,
        hasntLogisticsfinished: false,
        hasLogisticsOrders: [],
        hasLogisticsPageNum: 1,
        hasLogisticsfinished: false,
      }
    },
    computed: {
      user() { return this.$store.state.authUser || {} },
      userId() {
        if (!this.user ||!this.user.user) return ''
        return this.user.user.id
      },
      openId() {
        if (!this.user ||!this.user.userWx) return ''
        return this.user.userWx.openid
      },
    },
    beforeMount() {
      // this.getOrderALL()
    },
    filters: {
      totalNum: function (orders) {
        if (!orders) return 0
        const nums = orders.map(order => order.quantity)
        if (!nums || !nums.length) return 0
        return nums.reduce((total, current) => total + current)
      },
      orderStatus: function (status) {
        // 0-已取消-10-未付款，20-已付款，30-超时， 40-已发货，50-交易成功，60-交易关闭
        const stus = status / 10
        const statusArr = ['订单已取消', '待付款', '等待卖家发货', '订单超时', '卖家已发货', '交易成功', '交易关闭']
        return statusArr[stus]
      }
    },
    methods: {
      async receivingGoods(id) {
        const resp = await this.$post('/api/platform/order/update', {id, status: 50})

        if (resp && resp.code === 200) {
          this.$toast.success('确认收货成功')
          this.getOrderALL()
        } else {
          this.$toast.fail('确认收货失败')
        }
      },
      remind() {
        this.$toast.success('已提醒卖家发货')
      },
      cancelOrder(order = {}) {
        const stus = status / 10

        this.$dialog.confirm({
          title: '',
          message: '取消订单？'
        }).then(() => {
          const data = { 
            id: order.orderNo, 
            status: 0, 
            userId: this.userId,
          }

          this.$post('/api/platform/order/update', data)
            .then(() => {
              this.$toast.success('操作成功')
              this.getOrderALL()
            })
            .catch(() => { this.$toast.fail('操作失败') })
          }).catch(() => {
        })

      },
      delOrder(order = {}) {
        this.$dialog.confirm({
          title: '',
          message: '删除订单？'
        }).then(() => {
          const data = { 
            id: order.orderNo,  
            userId: this.userId,
          }

          this.$post('/api/platform/order/delete', data)
            .then(() => {
              this.$toast.success('操作成功')
              this.getOrderALL()
            })
            .catch(() => { this.$toast.fail('操作失败') })
          }).catch(() => {
        })

      },
      pay(order) {
        const { payment, orderNo } = order || {}
        pay(payment, orderNo, this.userId, this.openId)
          .then(() => {
            this.getOrderALL()
          })
          .catch(() => {
          })
      },
      getOrderALL() {
        this.isLoading = true

        const data = {
          userId: this.userId,
          pageSize: this.pageSize,
          pageNum: this.pageNum,
        }
        this.$post('/api/platform/order/orderAllPage', data).then(resp => {
          this.isLoading = false
          const _list = resp.data.list || []
          _list.forEach(item => { item.updateTime =  new Date(item.updateTime).getTime()})
          _list.sort(compare('updateTime', false))
          if (_list.length < this.pageSize) this.finished = true
          this.orders = [...this.orders, ..._list]
          this.pageNum++
        })
      },
      getOrderByStatus(status = 70) {
        // 0-已取消-10-未付款，20-已付款，30-超时， 40-已发货，50-交易成功，60-交易关闭
        this.isLoading = true


        const index = status / 10
        const pageNumArr = ['', 'unpayPageNum', 'hasntLogisticsPageNum', '', 'hasLogisticsPageNum', '', '', 'pageNum']
        const finishedArr = ['', 'unpayfinished', 'hasntLogisticsfinished', '', 'hasLogisticsfinished', '', '', 'finished']
        const ordersArr = ['', 'unpayOrders', 'hasntLogisticsOrders', '', 'hasLogisticsOrders', '', '', 'orders']

        const [ pageNumKey, finishedKey, ordersKey ] = [ pageNumArr[index], finishedArr[index], ordersArr[index] ]

        const data = {
          userId: this.userId,
          status,
          pageSize: this.pageSize,
          pageNum: this[pageNumKey],
        }
        this.$post('/api/platform/order/orderAllPage', data).then(resp => {
          this.isLoading = false
          const _list = resp.data.list || []
          _list.forEach(item => { item.updateTime =  new Date(item.updateTime).getTime()})
          _list.sort(compare('updateTime', false))
          if (_list.length < this.pageSize) this[finishedKey] = true
          this[ordersKey] = [...this[ordersKey], ..._list]
          this[pageNumKey]++
        })
      },
    }
  }
</script>

<style lang='stylus' rel='stylesheet/stylus' scoped>

@import '~assets/stylus/variable.styl'
 
section
  min-height 100vh
.loading
  padding-top 0.5rem
  text-align center
  .van-loading
    display inline-block
.order
  margin 1rem
  padding 1rem 0
  background-color $color-white
  border-radius 10px
  .order-status
    padding-right 1rem
    text-align right
    color $color-main
  .total
    padding-right 1rem
    text-align right
    line-height 2
  .control
    padding 1rem
    text-align right
    &>*
      margin-left 1rem
</style>
